package com.sumer.psychology.blog.application.query;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import com.sumer.psychology.common.persistence.mongodb.AbstractMongoRepository;

/**
 * 博客目录查询服务
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/10/21
 * Time: 11:03
 */
public class CategoryQueryApplicationService extends AbstractMongoRepository {
    private static final String CATEGORY_LIST = "sumer_category_list";
    private static final String CATEGORY = "sumer_category";

    @Override
    protected String dbName() {
        return CATEGORY_LIST;
    }

    /**
     * 列出作者博客的所有目录
     *
     * @param authorId id
     * @return json
     */
    public String listCategoriesOf(String authorId) {
        DBObject category = findOne(authorId);
        if (category != null) {
            return JSON.serialize(category.get("categories"));
        }
        return "[]";
    }

    /**
     * 查找唯一category
     *
     * @param categoryId id
     * @return json
     */
    public DBObject findCategoryById(String categoryId) {
        DBObject category = db()
                .getCollection(CATEGORY)
                .findOne(idCondition(categoryId), new BasicDBObject().append("_id", 1).append("name", 1));
        if (category == null) {
            return new BasicDBObject("name", "未分类");
        }
        return category;
    }
}
